package com.edu.interceptor;

import com.edu.entity.HfdUserInfo;
import com.edu.utils.JsonUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserInfoInterceptor implements HandlerInterceptor {

    private static ThreadLocal<HfdUserInfo> userInfo = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //获取用户信息
        String token = request.getHeader("token");
        try {
            if (!StringUtils.isEmpty(token) && !token.equals("null")) {
                HfdUserInfo hfdUserInfo = JsonUtils.toBean(token, HfdUserInfo.class);
                //放入到ThreadLocal中
                userInfo.set(hfdUserInfo);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        userInfo.remove();

    }

    public static HfdUserInfo getUserInfo() {

        return userInfo.get();

    }

}
